package com.itmuch.common.feignset.config;

import com.dianping.cat.Cat;
import com.itmuch.common.cat.CatMsgConstants;
import com.itmuch.common.context.QfContext;
import com.itmuch.common.context.QfContextUtil;
import com.itmuch.common.feignset.hystix.QfHystrixRequestContext;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

public class TokenInterceptor implements RequestInterceptor {
	private Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);
	@Override
	public void apply(RequestTemplate template) {
//		 template.header("X-Forwarded-For", "origin.host.com");
//		 template.header("test", "xiaocai");
		logger.info("ThreadName2;"+Thread.currentThread().getName());

		QfContext context = QfContextUtil.getQfcontext();
		//因为变量使用的是HystrixRequestContext.getContextForCurrentThread().state; 这个是上面父类的状态；state里面是根据上面的请求id来做的；
		if(context == null){
			  //获取当前请求的上下文逻辑,发起新的client要传递上下文逻辑过去
			if(HystrixRequestContext.getContextForCurrentThread() !=null){
				context = QfHystrixRequestContext.getRequestVariableDefaultInstance().get();
			}
		}
		if(context != null){
			//来源于其他系统走其他的header
			//template.header(CommonConstant.CONSTANT_TOKEN_HEADER_NAME,context.getUserToken());
		}
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		Object root = requestAttributes.getAttribute(Cat.Context.ROOT, 0);
		if(root!=null){
			String rootId = requestAttributes.getAttribute(Cat.Context.ROOT, 0).toString();
			String childId = requestAttributes.getAttribute(Cat.Context.CHILD, 0).toString();
			String parentId = requestAttributes.getAttribute(Cat.Context.PARENT, 0).toString();
			template.header(Cat.Context.ROOT, rootId);
			template.header(Cat.Context.CHILD, childId);
			template.header(Cat.Context.PARENT, parentId);
			template.header(CatMsgConstants.APPLICATION_KEY, Cat.getManager().getDomain());
			template.header("X-CAT-TRACE-MODE","true");
			logger.info(" start feign : " + template.method() + " model : rootId = " + rootId + " parentId = " + parentId + " childId = " + childId);
		}
	}
}
